import cv2
import pyautogui
from ultralytics import YOLO
import time
import sys
import os
import subprocess  # 确保导入 subprocess 模块
from moveFb模块 import movefb
import win32gui
import 检测框模块
from find_class_module import find_class_and_perform_action
from yolo2.find_and_perform_action_module import find_and_perform_action
from yolo2.mouse_move_module import move_mouse_to_target_class
from yolo2.yolo找图模块 import click_target_image
from yolo2.循环找图模块 import run_action_condition_found, run_action_condition_not_found
import subprocess
import sys

if hasattr(检测框模块, 'MODULE_LOADED') and 检测框模块.MODULE_LOADED:
    print("检测框模块已正确加载")
else:
    print("检测框模块加载失败")

def draw_detection_boxes(screenshot, results):
    for result in results:
        boxes = result.boxes.cpu().numpy()
        for box in boxes:
            class_id = int(box.cls[0])
            x1, y1, x2, y2 = box.xyxy[0].astype(int)
            center_x = int((x1 + x2) / 2)
            center_y = int((y1 + y2) / 2)

            # 在图像上绘制检测框
            cv2.rectangle(screenshot, (x1, y1), (x2, y2), (0, 255, 0), 2)
            cv2.putText(screenshot, f"Class {class_id}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

    return screenshot

# 禁用 pyautogui 的安全保护机制
pyautogui.FAILSAFE = False

# 加载 YOLOv8n 模型并指定使用GPU
model = YOLO(r"h:\yol\yolo\v11\runs\detect\train20\weights\best.pt").to('cuda')

hwnd = 检测框模块.find_window()
if hwnd is None:
    print("未找到标题中包含'梦幻西游'的窗口")
else:
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    window_width = right - left
    window_height = bottom - top


    def action_a():
        move_mouse_to_target_class(hwnd, model, 89, -10, -10, 0.3)
        movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=89, offset_x=-10,
           offset_y=-10, 置信度=0.3, click_type='left' )
        time.sleep(1)
    find_class_and_perform_action(hwnd, model, 1, action_a)

    movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=5, offset_x=-10, offset_y=-10,
           置信度=0.3, click_type='left')
    def action():  # 找到就
        movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=1, offset_x=-10, offset_y=-10,
               置信度=0.3, click_type='left')
    find_and_perform_action(hwnd, model, 1, action)


    def action():  # 找到就
        movefb(hwnd, left, top, window_width, window_height, model, 要点击的目标类=5, offset_x=-10,
               offset_y=-10, 置信度=0.3, click_type='left',)
    find_and_perform_action(hwnd, model, 5, action)
    subprocess.run([sys.executable, "主程序.py"], check=False)

    sys.exit()




cv2.destroyAllWindows()